using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Collections;

namespace Ent.Web.Helper
{
    public enum EllipseDirection { Begin, End }
    public class StringHelper
    {
        public static string RestrictMaxChar(string text, int length)
        {
            return RestrictMaxChar(text, length, EllipseDirection.End);
        }
        public static string RestrictMaxChar(string text, int length, EllipseDirection dir)
        {
            if (text == null || text.Length <= length || length == -1)
                return text;
            else
            {
                if (dir == EllipseDirection.End)
                {
                    string textPart = text.Substring(0, length);
                    return textPart + "...";
                }
                else
                {
                    string textPart = text.Substring(text.Length - length);
                    return "..." + textPart;
                }
            }
        }
        public static string ConvertUnitToString(Unit u)
        {
            return u.Type == UnitType.Percentage
                    ? u.Value.ToString() + "%"
                    : u.Value.ToString() + "px";
        }
        public static string ConvertColorToHexString(Color col)
        {
            return ColorTranslator.ToHtml(col);
        }
        public static void ConvertToHtmlText(ref string plainText)
        {
            if (plainText == null)
                plainText = "";
            plainText = plainText.Replace(System.Environment.NewLine, "<br />");
            plainText = plainText.Replace("\t", "&npsp;&npsp;&npsp;&npsp;");
        }
        public static string[] BitToArray(int bitnumber)
        {
            ArrayList list = new ArrayList();
            if (bitnumber > 1024)
                throw new Exception("BitToArray does not support number greater than 1024.");
            int[] arr = new int[] { 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024 };
            foreach (int i in arr)
            {
                if ((bitnumber & i) > 0)
                    list.Add(i.ToString());
            }
            string[] retValue = new string[list.Count];
            list.CopyTo(retValue);
            return retValue;
        }
        public static string ConvertToString(object obj)
        {
            return (obj == null ? "" : obj.ToString());
        }
    }
}
